// 机构库 - 列表
import React from 'react';
import { observer, useLocalStore } from 'mobx-react-lite';
import { Link } from 'react-router-dom';
import { Card, Form, Row, Col, Button, Input, Table, Modal, message, Select } from 'antd';
import {
  SearchOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import * as listApi from '~/apis/institution/listApi';
import * as detailApi from '~/apis/institution/detailApi';
import AjaxSelect from '~/components/AjaxSelect';
import { getColumns } from './pageConfig';
import './index.local.sass';

const cardConfig = {
  size: 'small' as const,
  bordered: false,
};

const FormItem = Form.Item;
const { confirm } = Modal;

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

const modalFormLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 19, offset: 1 },
};

const showTotal = (total: number) => `Total: ${total}`;

const { Option } = Select;

const InstitutionList = observer(() => {
  const state = useLocalStore(() => ({
    loading: false,
    tableList: {
      data: [],
      pageNo: 1,
      pageSize: 10,
      totalCount: 0,
      totalPage: 0,
    },
    getData: {},
    userName: '',
    orgName: '',
    orgId: '', // 机构id
    visibleFlag: false,
  }));

  const [form] = Form.useForm();
  const [modalForm] = Form.useForm(); // modal中的表单实例

  const doQuery = (curPage: number = 1) => {
    state.tableList.pageNo = curPage;

    const { pageNo, pageSize } = state.tableList;

    const params = {
      pageNum: pageNo,
      pageSize,
      ...state.getData,
    };

    state.loading = true;

    listApi.getList(params).then((res) => {
      state.tableList = {
        ...state.tableList,
        data: res.data,
        totalCount: res.pageInfo.total,
        totalPage: res.pageInfo.totalPages,
      };
    }).finally(() => {
      state.loading = false;
    });
  };

  const onSearch = (values: any) => {
    state.getData = values;

    doQuery(1);
  };

  const onReset = () => {
    form.resetFields();

    onSearch({});
  };

  // 删除
  const deleteItem = (id: number | string) => {
    confirm({
      title: 'Do you Want to delete this institution?',
      onOk() {
        listApi.deleteItem(id).then(() => {
          message.success('delete success');
          doQuery(1);
        });
      },
    });
  };

  // 身份审核确认
  const handleAuditConfirm = (formData: any) => {
    state.visibleFlag = false;
    detailApi.handleAuditConfirm(formData).then(() => {
      message.success('audit success');
      doQuery(1);
    });
  };

  // 身份审核取消
  const handleAuditCancel = () => {
    state.visibleFlag = false;
  };

  // 获取表单数据 form.validateFields()
  const onOk = () => {
    modalForm.validateFields().then((values) => {
      values.orgId = state.orgId; // 点击所在行的机构id
      values.pass = values.pass === 1; // 审核是否通过
      handleAuditConfirm(values);
    });
  };

  // Modal属性
  const modalOption: any = {
    title: 'Review',
    visible: state.visibleFlag,
    width: 700,
    forceRender: true, // 强制渲染
    // destroyOnClose: true, // 关闭时销毁modal子元素
    onOk,
    onCancel: handleAuditCancel,
  };

  // 显示弹框
  const showAuditModal = (id: string) => {
    state.visibleFlag = true;
    state.orgId = id; // 机构id
    modalForm.resetFields(); // 清空modal弹框值
    detailApi.getUserInfo({ orgId: state.orgId }).then((res) => {
      state.userName = res.data.username ? res.data.username : '';
      state.orgName = res.data.orgName ? res.data.orgName : '';
    });
  };

  const columns = getColumns({ deleteItem, showAuditModal });

  const { loading, tableList: {
    pageNo, totalCount, pageSize, data,
  } } = state;

  const tableOption: any = {
    loading,
    columns,
    pagination: {
      current: pageNo,
      total: totalCount,
      pageSize,
      size: 'small',
      showQuickJumper: true,
      showTotal,
      onChange: (curPage: number) => {
        doQuery(curPage);
      },
    },
    dataSource: data || [],
    rowKey: 'id',
    size: 'small',
  };

  React.useEffect(() => {
    doQuery(1);
  }, []);

  return (
    <div>
      <Card {...cardConfig} className="search-card">
        <Form form={form} onFinish={onSearch}>
          <Row>
            <Col span={6}>
              <FormItem
                name="countryId"
                {...formItemLayout}
              >
                <AjaxSelect
                  placeholder="Country/Region"
                  type="countryList"
                />
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem
                name="auditStatusId"
                {...formItemLayout}
              >
                <AjaxSelect
                  placeholder="Institution Status"
                  type="auditStatus"
                />
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem
                name="industryId"
                {...formItemLayout}
              >
                <AjaxSelect
                  placeholder="Industry"
                  type="industryList"
                />
              </FormItem>
            </Col>
            <Col span={6}>
              {/* 专业 */}
              <FormItem
                name="specialityId"
                {...formItemLayout}
              >
                <AjaxSelect
                  placeholder="Main Business"
                  type="specialityList"
                />
              </FormItem>
            </Col>
          </Row>

          <Row>
            <Col span={6}>
              <FormItem
                name="orgType"
                {...formItemLayout}
              >
                <AjaxSelect
                  placeholder="institution type"
                  type="orgType"
                />
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem
                name="name"
                {...formItemLayout}
              >
                <Input
                  allowClear={true}
                  prefix={
                    <SearchOutlined className="text-gray-400" />
                  }
                />
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem {...formItemLayout}>
                <Button
                  type="primary"
                  className="mr-2"
                  htmlType="submit"
                >
                  Search
                </Button>

                <Button className="mr-2" onClick={onReset}>
                  Reset
                </Button>
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card {...cardConfig} className="card">
        <div className="mb-4">
          <Link to={'/institution/add'}>
            <Button
              className="mr-2"
              icon={
                <PlusOutlined/>
              }
            >
              New Institution
            </Button>
          </Link>
        </div>

        <Modal
          {...modalOption}
        >
          <Form
            {...modalFormLayout}
            form={modalForm}
          >
            {/* line1 */}
            <Form.Item
              label="User name:"
            >
              <span>{state.userName}</span>
            </Form.Item>

            {/* line2 */}
            <Form.Item
              label="Institution Name:"
            >
              <span>{state.orgName}</span>
            </Form.Item>

            {/* line3 */}
            <Form.Item
              label="Pass:"
              name="pass"
              rules={[{ required: true }]}
            >
              <Select
                placeholder="Please select"
                allowClear
              >
                <Option key={1} value={1}>true</Option>
                <Option key={0} value={0}>false</Option>
              </Select>
            </Form.Item>

            {/* line4 */}
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.pass !== currentValues.pass}
            >
              {({ getFieldValue }) => (getFieldValue('pass') === 1 ? (
                <Form.Item name="roleId" label="Role:" rules={[{ required: true }]}>
                  <AjaxSelect
                    placeholder="Please select"
                    type="role"
                  />
                </Form.Item>
              ) : <></>)}
            </Form.Item>

            {/* line5 */}
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.pass !== currentValues.pass}
            >
              {({ getFieldValue }) => (getFieldValue('pass') === 0 ? (
                <Form.Item name="rejectReason" label="Rejected reason:" rules={[{ required: true }]}>
                  <Input.TextArea placeholder="Please input" rows={4} />
                </Form.Item>
              ) : <></>)}
            </Form.Item>

          </Form>
        </Modal>

        <Table
          {...tableOption}
        />
      </Card>
    </div>
  );
});

export default InstitutionList;
